package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"video-social/cache"
	"video-social/models"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size

	var video []models.Video
	redis_key := "video_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("videos").Offset(offset).Limit(size).Find(&video)
		jsonData, _ := json.Marshal(video)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &video)
	}

	var count int64
	models.DB.Model(&models.Video{}).Count(&count)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"count": count,
			"video": video,
		},
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")

	var video []models.Video
	redis_key := "user_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", id).First(&video)
		jsonData, _ := json.Marshal(video)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &video)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": video,
	})
	return
}

func Like(c *gin.Context) {
	userId, _ := strconv.Atoi(c.Query("user_id"))
	videoId, _ := strconv.Atoi(c.Query("video_id"))

	var like models.Like
	err := models.DB.Where("user_id=? and video_id=?", userId, videoId).First(&like).Error
	if err == nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能重复点赞",
		})
		return
	}

	like = models.Like{
		VideoId: videoId,
		UserId:  userId,
	}

	tx := models.DB.Begin()
	err = tx.Create(&like).Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "点赞添加失败",
		})
		return
	}

	var video models.Video
	err = tx.Where("id=?", videoId).First(&video).Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据不存在",
		})
		return
	}

	video.LikeCount++
	err = tx.Save(&video).Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "点赞更新失败",
		})
		return
	}
	tx.Commit()
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "点赞成功",
	})
	return

}
